package com.sh.data.engine.domain.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sh.data.engine.common.util.ServletUtils;
import com.sh.data.engine.domain.annotation.ProjectStatisticAspect;
import com.sh.data.engine.domain.authority.service.StatisticService;
import com.sh.data.engine.repository.dao.normalization.index.IndexMapper;
import com.sh.data.engine.repository.dao.normalization.index.entity.IndexEntity;
import com.sh.data.engine.repository.dao.workspace.index.ProjectStatisticsMapper;
import com.sh.data.engine.repository.dao.workspace.index.entity.ProjectStatisticsEntity;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Aspect
@Service(value = "index")
public class IndexStatisticServiceImpl implements StatisticService {
    private static final Logger log = LoggerFactory.getLogger(ProjectStatisticAspect.class);

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private ProjectStatisticsMapper projectStatisticsMapper;

    @Override
    @Around("myProjectStatisticExecution()")
    public Long statistic() {
        return indexMapper.selectCount(new LambdaQueryWrapper<IndexEntity>()
                .eq(IndexEntity::getProjectId, ServletUtils.getProjectId()));
    }

    @Override
    public void update(Long before, Long after) {
        if (!Objects.equals(after, before)) {
            LambdaUpdateWrapper<ProjectStatisticsEntity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(ProjectStatisticsEntity::getProjectId, ServletUtils.getProjectId());
            wrapper.setSql("index_num = index_num + " + (after - before));
            projectStatisticsMapper.update(wrapper);
        }
    }


}
